package com.party.admin.task;

import com.party.admin.biz.wechat.WechatBizService;
import com.party.admin.web.dto.input.wechat.GetTicketResponse;
import com.party.api.dto.wechatPlatform.requst.RefreshAuthorizerTokenRequest;
import com.party.api.dto.wechatPlatform.response.RefreshAuthorizerTokenResponse;
import com.party.api.service.wechatPlatform.IWechatPlatformService;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.DeployType;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.model.wechatPlatform.WechatOpenPlatform;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.core.service.wechatPlatform.IWechatOpenPlatformService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 微信开放平台定时任务
 * Created by wei.li
 *
 * @date 2017/8/28 0028
 * @time 18:36
 */
@Component(value = "quartzWechatPlatform")
public class QuartzWechatPlatform {

    @Autowired
    private IWechatPlatformService wechatPlatformService;

    @Autowired
    private IWechatOpenPlatformService wechatOpenPlatformService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Value("#{wechat_platform['wechat.platform.appId']}")
    private String componentAppid;

    @Value("#{wechat_platform['wechat.platform.appSecret']}")
    private String componentAppsecret;

    @Autowired
    private WechatBizService wechatBizService;

    protected static Logger logger = LoggerFactory.getLogger(QuartzWechatPlatform.class);


    /**
     * 刷新开放平台
     */
    public void refreshComponent(){
        logger.info("刷新开放平台token任务启动");
        WechatOpenPlatform wechatOpenPlatform = wechatOpenPlatformService.get();
        try {
            String token
                    = wechatPlatformService.getAccessToken(componentAppid, componentAppsecret,
                    wechatOpenPlatform.getComponentVerifyTicket());
            if (null != token){
                wechatOpenPlatform.setComponentAccessToken(token);
                wechatOpenPlatform.setUpdateDate(DateUtils.now());
                wechatOpenPlatformService.update(wechatOpenPlatform);
            }
        } catch (Exception e) {
           logger.error("刷新开放平台token异常", e);
        }

    }


    /**
     * 刷新授权公众号
     */
    public void refreshAuthorizer(){
        logger.info("刷新授权公众号token任务启动");
        WechatOpenPlatform wechatOpenPlatform = wechatOpenPlatformService.get();
        WechatOpenMember w = new WechatOpenMember();
        w.setDeployType(DeployType.AUTHORIZATION.getCode());
        List<WechatOpenMember> list = wechatOpenMemberService.list(w);
        for (WechatOpenMember wechatOpenMember : list){
            try {
                RefreshAuthorizerTokenRequest request = new RefreshAuthorizerTokenRequest();
                request.setComponentAppid(componentAppid);
                request.setAuthorizerAppid(wechatOpenMember.getAuthorizerAppid());
                request.setAuthorizerRefreshToken(wechatOpenMember.getAuthorizerRefreshToken());
                RefreshAuthorizerTokenResponse response
                        =  wechatPlatformService.refreshAuthorizerToken(request, wechatOpenPlatform.getComponentAccessToken());
                if (null != response && StringUtils.isNotEmpty(response.getAuthorizerRefreshToken())
                        && StringUtils.isNotEmpty(response.getAuthorizerAccessToken())){
                    wechatOpenMember.setAuthorizerAccessToken(response.getAuthorizerAccessToken());
                    wechatOpenMember.setAuthorizerRefreshToken(response.getAuthorizerRefreshToken());

                    try {
                        GetTicketResponse getTicketResponse = wechatBizService.getTicket(wechatOpenMember.getAuthorizerAccessToken());
                        if (null != getTicketResponse && null != getTicketResponse.getTicket()){
                            wechatOpenMember.setTicket(getTicketResponse.getTicket());
                        }
                    } catch (Exception e) {
                        logger.error("获取ticket异常", e);
                    }

                    wechatOpenMember.setUpdateDate(DateUtils.today());
                    wechatOpenMemberService.update(wechatOpenMember);

                    if (StringUtils.isNotEmpty(wechatOpenMember.getAuthorizerAppid()) && wechatOpenMember.getAuthorizerAppid().equals("wx1c8409c404069a43")) {
                        logger.info(getClass() + "   更新wechatOpenMember的{}token信息", wechatOpenMember.getAuthorizerAppid());
                    }
                }
            } catch (Exception e) {
                logger.error("刷新授权公众号信息异常", e);
                continue;
            }
        }
    }
}
